package com.ng.framework.persistence;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

@Service
public abstract class NGListingService extends NGBasePersistence {

	public <T> T getHydratedBean(NGListingBean ngListingBean, Class<T> clazz) {

		return (T) getHibernateTemplate().get(clazz, ngListingBean.getId());

	}

	public List<NGListingBean> getList(final NGListName listName) {
		return this.getList(listName, null, true, null);
	}

	public List<NGListingBean> getList(final NGListName listName, String orderBy, final Integer maxResults) {
		return this.getList(listName, orderBy, true, maxResults);
	}

	public List<NGListingBean> getList(final NGListName listName, String orderBy, boolean asc, final Integer maxResults) {

		final List<NGListingBean> listingBeans = new ArrayList<NGListingBean>();

		final StringBuilder query = new StringBuilder();

		final String filter = listName.getFilter();

		final String alias = listName.getClazz().getSimpleName();

		query.append("select ");
		query.append(alias + "." + listName.getColumnId());
		query.append(",");
		query.append(alias + "." + listName.getColumnDescription());
		query.append(" FROM ");
		query.append(listName.getClazz().getName());
		query.append(" " + alias);

		boolean hasFilter = !StringUtils.isEmpty(filter);

		if (hasFilter) {
			query.append(" WHERE ");

			query.append(alias + "." + listName.getColumnDescription());
			query.append(" LIKE '%");
			query.append(filter);
			query.append("%'");

		}

		query.append(" order by  ");
		if (StringUtils.isEmpty(orderBy)) {
			query.append(alias + "." + listName.getColumnDescription() + (asc ? " asc " : " desc "));
		} else {
			query.append(alias + "." + orderBy + (asc ? " asc " : " desc "));
		}

		final List listingBeanObjects = getHibernateTemplate().find(query.toString());

		NGListingBean bpListingBean;
		for (final Iterator iterator = listingBeanObjects.iterator(); iterator.hasNext();) {
			final Object[] listingBeanObject = (Object[]) iterator.next();
			bpListingBean = new NGListingBean(new Long(listingBeanObject[0].toString()), listingBeanObject[1].toString());
			listingBeans.add(bpListingBean);
		}

		return listingBeans;

	}
}
